<?php

namespace App\Http\Controllers;

use App\Models\Wechat;
use Illuminate\Http\Request;

class WechatController extends Controller{


    /**
     * 获取所有公众号
     * @return \Illuminate\Http\JsonResponse
     */
    public function all(){
        $data = Wechat::select('avatar','name','type','original_id','wechat')
            ->get();
        return $this->returnJson(0,'',$data);
    }

    /**
     * 公号详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function info(Request $request){
        $account = (string)$request->get('account');
        if(empty($account)){
            return $this->returnJson(1,'参数错误');
        }
        $info = Wechat::select('id','account','original_id','password','wechat',
            'name','app_id','secret','token','aes_key','api_url',
            'type','is_auth','avatar','qcode','follow_replay',
            'follow_matter_id','delay_replay','delay_matter_id',
            'replay_at','activity','activity_id','scan_at')
            ->where('original_id',$account)->first();
        if($info){
            return $this->returnJson(0,'',$info);
        }
        return $this->returnJson(1,'抱歉，数据不存在');
    }

    /**
     * 更新公众号信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request){
        try {
            $data = $request->all();
            if(!isset($data['id'])){
                //重复
                $info = Wechat::where('original_id',$data['account'])->first();
                if($info){
                    return $this->returnJson(1,'该邮箱账号已经存在，请勿重复添加');
                }
                $data['avatar'] = 'http://xuehai.bh/img/default.png';
                $result = Wechat::create($data);
                $result->update([
                    'api_url'=>env('APP_URL').'replay?id='.$result['id']
                ]);
                return $this->returnJson(0, '新增数据成功，页面即将跳转...');
            }else{
                //先查后更
                $info = Wechat::find($data['id']);
                if(empty($info)){
                    return $this->returnJson(1,'抱歉，数据不存在');
                }
                $info->update($data);
                return $this->returnJson(0, '更新数据成功，页面即将跳转...',$data);
            }
        } catch (\Exception $e) {
            return $this->returnJson(1, $e->getMessage());
        }
    }

}